#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QDebug>
#include "nrf_ioctrl.h"


#define NRF2410_NOD  "/dev/nrf2410"


MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    nrf_fd = ::open(NRF2410_NOD, O_RDWR|O_NDELAY);
    if(nrf_fd < 0){
        qDebug()<<"open nrf error";
        //exit(-1);
    }

    my_lus->init_prase();
    connect(my_lus, SIGNAL(lus_requst_send(QByteArray)), this, SLOT(send_lus_cmd(QByteArray)));
    connect(my_tcp, SIGNAL(recive_lus_pack(QString)), my_lus, SLOT(lus_exec_pack(QString)));
    connect(my_tcp, SIGNAL(read_msg(QByteArray)), this, SLOT(readMsg(QByteArray)));
    my_tcp->aes_tcp_init();

    p_order_list = init_order_list();

    //photo send
    connect(thread_get_image1, SIGNAL(UpdateSignal(QImage, QString)),this, SLOT(flushBuff(QImage, QString)));

    //接收命令
    udp_receiver = new QUdpSocket(this);
    udp_receiver->bind(8849, QUdpSocket::ShareAddress);
    connect(udp_receiver,SIGNAL(readyRead()),this,SLOT(processPendingDatagram()));

    local_udp = new QUdpSocket(this);
    local_udp->bind(QHostAddress::LocalHost, 4399, QUdpSocket::ShareAddress);
    connect(local_udp,SIGNAL(readyRead()),this,SLOT(do_local_udp()));

    thread_get_image1->name = "/dev/video2";
    thread_get_image1->start();


    thread_get_image2->name = "/dev/video3";
   // thread_get_image2->start();

  }

void MainWindow::readMsg(QByteArray b_data)
{
    do_cmd(b_data);
    qDebug()<<b_data;
    my_lus->lus_do_cmd(b_data);
}

void MainWindow::send_lus_cmd(QByteArray cmd)
{
   // qDebug()<<"send lus cmd :" << cmd;
    my_tcp->sendMessage(cmd, ENCRYPT_YES);

}

void MainWindow::do_local_udp()
{

     while(local_udp->hasPendingDatagrams())  //拥有等待的数据报
    {
        QByteArray datagram; //拥于存放接收的数据报
        //让datagram的大小为等待处理的数据报的大小，这样才能接收到完整的数据
        datagram.resize(local_udp->pendingDatagramSize());
        //接收数据报，将其存放到datagram中
        local_udp->readDatagram(datagram.data(),datagram.size());
        //将数据报内容显示出来

        if(datagram.size() < sizeof (struct _st_sensor)){

            qDebug()<<"error sensor data";

            return;
           }

        struct _st_sensor * p_sensor = (struct _st_sensor *)datagram.data();
       // qDebug() << "local udp recive: "<<datagram;
        qDebug() << "adc: "<<(int)p_sensor->adc_v;
        qDebug() << "hum1: "<<(int)p_sensor->hum1;
        qDebug() << "tmp_de "<<(int)p_sensor->tmp_de;
        qDebug() << "fix id: "<<(int)p_sensor->fix_id;

        for(int i=0; i<4; i++)
                qDebug()<<"tmp "<<(int)p_sensor->tmp[i];
        QByteArray sensor_data;
        QBuffer bf(&sensor_data);
        bf.open(QIODevice::WriteOnly);
        bf.write((char *)p_sensor, sizeof (struct _st_sensor));
        bf.close();

        sensor_data = sensor_data.toBase64();

        QByteArray cmd;
        cmd = "<user_msg type=\"sensor_data\" body=\"xxx\">";
        cmd.replace("xxx", sensor_data);
        my_tcp->sendMessage(cmd, ENCRYPT_YES);
    }


}


void MainWindow::processPendingDatagram()
{
    while(udp_receiver->hasPendingDatagrams())  //拥有等待的数据报
    {
        QByteArray datagram; //拥于存放接收的数据报
        //让datagram的大小为等待处理的数据报的大小，这样才能接收到完整的数据
        datagram.resize(udp_receiver->pendingDatagramSize());
        //接收数据报，将其存放到datagram中
        udp_receiver->readDatagram(datagram.data(),datagram.size());
        //将数据报内容显示出来

        qDebug() << "udp recive: "<<datagram;
    }


}


void MainWindow::com_init(void)
{

    /*
    my_serialPort = new QSerialPort(this);

    //my_serialPort->setPortName(SERIAL_NAME);

    my_serialPort->open(QIODevice::ReadWrite);
    my_serialPort->setBaudRate(115200 );//波特率
    my_serialPort->setDataBits( QSerialPort::Data8 );//数据字节，8字节
    my_serialPort->setParity( QSerialPort::NoParity );//校验，无
    my_serialPort->setFlowControl( QSerialPort::NoFlowControl );//数据流控制,无
    my_serialPort->setStopBits( QSerialPort::OneStop );//一位停止位
    */
/*
    timer = new QTimer(this);
    connect( timer, SIGNAL( timeout() ), this, SLOT( readMyCom() ) );
    timer->start(200);//每秒读一次
    */


}


void Thread_photo::run()
{

    th_udp_send = new QUdpSocket();
    get_image_flag = 1;

    QString node_name = this->name;


    pd.dev_name = node_name.toLatin1().data();


    int flag = init_dev(&pd);

    if (flag == -1) {
        // QMessageBox::information(this,tr("Tip"),tr("no device"));
        return;
    }else if (flag == -2) {
        //QMessageBox::information(this,tr("Tip"),tr("device is wrong"));
        return;
    }else if (flag == -3) {
        //QMessageBox::information(this,tr("Tip"),tr("can not open device"));
        return;
    }


    //添加一个for循环
    do{

        if(get_image_flag == 1){

            read_frame (&pd);
   // for(int i=0; i<8; i+=2){

            image_my.loadFromData((const uchar *)pd.buffers[pd.buf.index].start,pd.buffers[pd.buf.index].length);

            /*
            QByteArray ba;

            QBuffer buf(&ba);

            image_my.save(&buf,"JPG",40);

            QByteArray xml_info;
            xml_info = "<user_msg type=\"tank_image\" ch=\"xxx\" body=\"";
            xml_info.replace("xxx", node_name.toLatin1());
            QByteArray hexed = ba.toBase64();
            xml_info += hexed;

            xml_info += "\" />";

            th_udp_send->writeDatagram("#udp test!!", QHostAddress("beijg.3322.org"),8848);

            th_udp_send->writeDatagram(xml_info, QHostAddress("beijg.3322.org"),8848);
            */

            emit UpdateSignal(image_my, node_name);

 //   }
               /*
        QFile t_p("/root/tt.jpg");
        t_p.open(QIODevice::WriteOnly|QIODevice::Truncate);
        t_p.write((char *)pd.buffers[pd.buf.index].start, (qint64)pd.buffers[pd.buf.index].length);
        t_p.close();
        qDebug()<<"save imag!";*/

            return_data(&pd);
        }

        msleep(60);

    }while(1);


}


// abandoned
void MainWindow::flushBuff(QImage image_my, QString node_name)
{



       QByteArray ba;

       QBuffer buf(&ba);

       image_my.save(&buf,"JPG",40);

       QByteArray xml_info;
       xml_info = "<user_msg type=\"tank_image\" ch=\"xxx\" body=\"";
       xml_info.replace("xxx", node_name.toLatin1());
       QByteArray hexed = ba.toBase64();
       xml_info += hexed;

       xml_info += "\" />";

       //udp_send->writeDatagram(xml_info, QHostAddress("222.18.137.68"),8848);
       my_tcp->sendMessage(xml_info, ENCRYPT_NO);
}



MainWindow::~MainWindow()
{


    delete ui;
}


void MainWindow::do_cmd(QByteArray cmd)
{

   QDomDocument xml;
   xml.setContent(cmd);

   QDomElement rootnode = xml.documentElement();


    if(rootnode.tagName() == "user_msg"){    //传输的文本信息

       //qDebug()<<"user_msg";

       if(rootnode.attributeNode("type").value() == "tank_cmd"){

           QString cmd_data = rootnode.attributeNode("body").value();
           // qDebug()<<cmd_data;

            if(cmd_data == "camera_on"){

                thread_get_image1->get_image_flag = 1;

            }else if (cmd_data == "camera_off") {

                thread_get_image1->get_image_flag = 0;
            }
           up_cook_data(cmd_data.toLatin1().data());

           return;
       }

       if(rootnode.attributeNode("type").value() == "tk_nrf_check"){

           ioctl(nrf_fd, NRF_CK);

           uint8_t nrf_connect_status = 254;

           ioctl(nrf_fd, NRF_CNT_STATUS, &nrf_connect_status);

           qDebug()<< "nrf status: " << nrf_connect_status;
            QByteArray cmd = tk_cmd;
            cmd.replace("arg1", "tk_nrf_status");

            if(nrf_connect_status == 1){
                cmd.replace("arg2", "connected");
            }else if (nrf_connect_status == 0) {
                cmd.replace("arg2", "disconnected");
            }

            qDebug()<<cmd;
            my_tcp->sendMessage(cmd, ENCRYPT_YES);




           return;
       }

   }

}



void MainWindow::on_pushButton_clean_clicked()
{
    ui->textBrowser->clear();
    QByteArray tmp = my_tcp->msg_tcp_socket->readAll();
    qDebug()<<tmp;
}

void MainWindow::on_pushButton_clicked()
{
    QString tmp ;
    tmp = ui->lineEdit_ming->text();

    my_tcp->sendMessage(tmp.toLatin1(), ENCRYPT_YES);

}


void MainWindow::up_cook_data(char *data)
{

    char tmp[20] = {0};


    tmp[0]='#';
    for(int i=0; i<4; i++){
        tmp[1+i]=data[4+i];
    }
    tmp[5] = '#';

   // nrf_send(tmp);

    struct slave_order * s_order;
    memset(&s_order, 0, sizeof (s_order));

    s_order = cook_data(data, 15);
    qDebug("\n s order status = %d \n", s_order->status);

    nrf_send((char *)s_order);
      for(int i=0; i<4; i++)
            qDebug("data = %x \n", s_order->data[i]);

    //for(int i=0; i<6; i++)qDebug(" cook %d ", tmp[i]);
/*
     cook_data(data, 15);

    while(p_order_list->next != NULL){

         //  for(int i=0; i<6; i++)qDebug(" cook %d ", ((char *)p_order_list->next->p_data)[i]);

                nrf_send((char *)p_order_list->next->p_data);
                queue_del(p_order_list);

            }
*/
}

/*发送命令*/
void MainWindow::nrf_send(char * data)
{

    if(nrf_fd > 0){
     //   qDebug()<<"write commend";

       ::write(nrf_fd, data, sizeof(char)*(3 + 4));
    }

}


